<?php
/**
 *  后台商品素材上传
 *
 *  1 复制原始文件到original_img目录
 *  2 压缩文件到指定大小,存入goods_img
 *  3 生成缩略图存入thumb_img
 *
 *  目录结构：
 *  webroot
 *        |- kldiy //所有商品素材
 *           |- [goods_id] //商品的编号
 *              |- orginal_img //上传的原始文件复本
 *              |- goods_img //压缩过的文件，用在程序中，文件尽可能的小，失真也没关系.需要加载快速。
 *              |- thumb_img //缩略图，100x100 px. PNG.
 *
 * 数据库表: goods_source
 * 
 *
 **/

require_once '../comm.php';
require_once '../log4.php';
include_once('../fm/comm.php');

//$log = new log4();

//$log->logMsg(__FILE__);
//$log->logMsg($_REQUEST);

$goods_id = isset($_REQUEST['gid'])?$_REQUEST['gid']:0; //商品ID

if($goods_id == 0){
	//$log->logMsg('商品编号未设置.');
	echo 'system error, not goods selected.';
	exit;
}

$filename = time();
$ext_name = '';

/** database */
$data = array(
'img_original'=>'original_img',
'img_url'=>'goods_img',
'thumb_url'=>'goods_thumb',
'goods_id'=>$goods_id,
'img_desc'=>'',
'hotarea'=>''
);

$original = '';


/* 检测目录是否存在 */
$dir = fm_check_dir($goods_id);

if($dir['g']==2){
	// 主目录是否存在
	//$log->logMsg('商品主目录创建失败。');
	echo 'system error, directory cannot created ';
	exit;
}else{

	$d = getimagesize($_FILES['Filedata']['tmp_name']);
	//$log->logMsg($_FILES['Filedata']);
	switch($d['mime']){
		case 'image/png' :
			$ext_name = '.png';
			break;
		case 'image/jpeg' :
			$ext_name = '.jpg';
			break;
		default :
			$ext_name = '.'.substr($_FILES['Filedata']['name'], -3, 3);
			break;
	}

	// 保存原始文件
	if($dir['g_o']!=2){
		$original = $dir['original_img'].'\\'.$goods_id.$filename.$ext_name;
		$re = move_uploaded_file($_FILES['Filedata']['tmp_name'], $original);
		$data['img_original'] = fm_get_img_addr($original);
		//$log->logMsg($data);
		if($re === false){
			$error = error_get_last();
			//$log->logMsg($error['message']);
		}
	}

	// 生成压缩文件
	if($dir['g_g']!=2){
		$dst_ = $dir['goods_img'].'\\'.$goods_id.$filename.$ext_name;

		if($ext_name == '.jpg'){
			$img = NewMagickWand();
			MagickReadImage($img, $original);
			MagickRemoveImageProfiles($img);
			MagickSetFormat($img, 'image/jpeg');
			MagickSetImageCompression($img, MW_JPEGCompression);
				
			//大于4M的文件以20%压缩
			if(MagickGetImageSize($img) > 4103762){
				MagickSetImageCompressionQuality($img, 20.0);
			}else{
				MagickSetImageCompressionQuality($img, 50.0);
			}
				
			$re = MagickWriteImage($img,$dst_);
			DestroyMagickWand($img);
			if($re === false){
				$error = error_get_last();
				//$log->logMsg($error['message']);
			}
		}else{
			//非jpg文件，直接复制到目标目录。
			if(!copy($original, $dst_)){
				$error = error_get_last();
				//$log->logMsg($error['message']);
			}
		}
		$data['img_url'] = fm_get_img_addr($dst_);
	}

	//生成缩略图
	if($dir['g_t']!=2){
		$dst_ = $dir['thumb_img'].'\\'.$goods_id.$filename.$ext_name;
		$re = system('convert -sample 100x100 '.$original.'  '.$dst_);
		if($re === false){
			$error = error_get_last();
			//$log->logMsg($error['message']);
		}
		$data['thumb_url'] = fm_get_img_addr($dst_);
	}

	
	//$log->logMsg($data);
	$insert = '';
	$col = '';
	$val = '';
	foreach($data as $k=>$v){
		$col .= $k.',';
		$val .= '"'.$v.'",';  
	}
	$query = 'insert into `'.$_table_goods_source.'` ('.rtrim($col,',').')values('.rtrim($val,',').')';
	//$log->logMsg($query);
	
	$myt = new thunder();
	$re = $myt->query($query);
	if($re){
		echo '1';
	}else{
		echo '0';
		$error = error_get_last();
		//$log->logMsg($error['message']);
	}
}


/**
 * 从绝对地址取出相对地址
 * 同时将windows的"\"转换为"/"
 */
function fm_get_img_addr($address){
	global $fm_rootdir;
	$fa = str_replace('\\','/',$fm_rootdir);
	$ca = str_replace('\\','/',$address);
	$result = str_replace($fa,'',$ca);
	$result = ltrim($result, '/');
	return $result;
}




/**
 *  检查文件目录
 *  返回数组，包括 目录路径
 **/
function fm_check_dir($goodsid){
	global $fm_rootdir;
	$error = 0; //错误信息
	$return = 0; //返回值
	$goods_dir = $fm_rootdir.'\\kldiy\\'.$goodsid; //商品素材目录
	$g = 0; //总目录标识
	$goods_original_dir = $goods_dir.'\\orginal_img'; //商品素材@原始图片目录
	$g1 = 0; //
	$goods_gimg_dir = $goods_dir.'\\goods_img'; //商品素材@压缩后图片目录
	$g2 = 0;
	$goods_thumb_img_dir = $goods_dir.'\\thumb_img'; //商品素材@缩略图目录
	$g3 = 0;

	if(!is_dir($goods_dir)){
		if(mkdir($goods_dir)){
			$g = 1;
		}else{
			$error = error_get_last();
			$goods_dir = $error['message'];
			$g = 2;
		}
	}

	// 原始
	if(!is_dir($goods_original_dir)){
		if(mkdir($goods_original_dir)){
			$g1 = 1;
		}else{
			$last_error = error_get_last();
			$goods_original_dir = $error['message'];
			$g1 = 2;
		}
	}

	//压缩
	if(!is_dir($goods_gimg_dir)){
		if(mkdir($goods_gimg_dir)){
			$g2 = 1;
		}else{
			$last_error = error_get_last();
			$goods_gimg_dir = $error['message'];
			$g2 = 2;
		}
	}

	//缩略
	if(!is_dir($goods_thumb_img_dir)){
		if(mkdir($goods_thumb_img_dir)){
			$g3 = 1;
		}else{
			$last_error = error_get_last();
			$goods_thumb_img_dir = $error['message'];
			$g3 = 2;
		}
	}

	$return = array(
							'goods_dir'=>$goods_dir,
							'original_img'=>$goods_original_dir,
							'goods_img'=>$goods_gimg_dir,
							'thumb_img'=>$goods_thumb_img_dir,
							'flag'=>$g.$g1.$g2.$g3,
							'g'=>$g,
							'g_o'=>$g1,
							'g_g'=>$g2,
							'g_t'=>$g3
	);

	return $return;
}


?>